package com.lh.lepay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lh.lepay.entity.Chathistory;
import com.lh.lepay.dao.ChathistoryDao;
import com.lh.lepay.entity.dto.ChatHistoryDto;
import com.lh.lepay.service.ChathistoryService;
import com.lh.lepay.utils.HttpStatus;
import com.lh.lepay.utils.ResponseData;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ChathistoryServiceImpl extends ServiceImpl<ChathistoryDao, Chathistory> implements ChathistoryService {



    @Resource
    private ChathistoryDao chathistoryDao;

    private final RedisTemplate<String, String> redisTemplate;
    private static final String KEY_PREFIX = "chat:memory:";

    public ChathistoryServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    public ResponseData insertChatHistoryStatment(Chathistory chathistory) {
        chathistory.setAnswerTime(new Date());
        // System.out.println(chathistory.toString());
        chathistoryDao.addChatHistoryStatment(chathistory);
        return new ResponseData(HttpStatus.SUCCESS,"保存成功！");
    }

    @Override
    public ResponseData insertChatHistoryDto(ChatHistoryDto chatHistoryDto) {
        System.out.println(chatHistoryDto);
        return null;
    }

    @Override
    public ResponseData queryChatHistoryDto(String uid) {
        // TODO 根据用户id查询对应用户的历史聊天记录
        // 查询聊天记录的Recording
        List<Chathistory> allRecords = chathistoryDao.selectBYRecording(uid);

        // 所有聊天记录
        QueryWrapper<Chathistory> queryWrapper = new QueryWrapper<>();
        List<Chathistory> chatHistoryList = chathistoryDao.selectList(queryWrapper);

        // 将 chathistoryList 转换为 Map，方便快速查找
        Map<String, List<Chathistory>> recordingMap = chatHistoryList.stream()
                .collect(Collectors.groupingBy(Chathistory::getRecording));

        // 构建前端需要的数据格式
        List<Map<String, Object>> historyList = new ArrayList<>();

        for (Chathistory record : allRecords) {
            String recordingId = record.getRecording();
            if (recordingMap.containsKey(recordingId)) {
                // 获取同一个Recording的所有记录
                List<Chathistory> groupedRecords = recordingMap.get(recordingId);

                // 构建消息列表
                List<Map<String, Object>> messages = new ArrayList<>();
                for (Chathistory groupedRecord : groupedRecords) {
                    // 用户提问部分
                    Map<String, Object> userMessage = new HashMap<>();
                    userMessage.put("role", "user");
                    userMessage.put("content", groupedRecord.getQuestion());

                    // 助理回答部分
                    Map<String, Object> assistantMessage = new HashMap<>();
                    assistantMessage.put("role", "assistant");
                    assistantMessage.put("content", groupedRecord.getAnswer());
                    assistantMessage.put("answerTime", groupedRecord.getAnswerTime());

                    // 添加到消息列表
                    messages.add(userMessage);
                    messages.add(assistantMessage);
                }

                // 构建对话记录
                Map<String, Object> chatRecord = new HashMap<>();
                chatRecord.put("title", generateTitle(groupedRecords.get(0).getQuestion())); // 根据Recording生成标题
                chatRecord.put("messages", messages);
                chatRecord.put("id", recordingId);

                log.info(chatRecord.toString());
                // 添加到历史记录列表
                historyList.add(chatRecord);
            }
        }
        log.info("聊天历史记录: {}", historyList);
        return new ResponseData(HttpStatus.SUCCESS, historyList);
    }

    @Override
    public void deleteHistoryByRecording(String recording) {
        LambdaQueryWrapper<Chathistory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Chathistory::getRecording,recording);
        chathistoryDao.delete(lambdaQueryWrapper);
    }


    @Override
    public ResponseData getChatLangMessageListByUsername(String username) {
        String pattern = KEY_PREFIX + username + ":*";


        Set<String> keys = redisTemplate.keys(pattern);
        List<Map<String, Object>> historyList = new ArrayList<>();

        ObjectMapper objectMapper = new ObjectMapper();

        if (keys != null) {
            for (String key : keys) {
                String history = redisTemplate.opsForValue().get(key);
                log.info("key:" + key);
                if (history != null && !history.isEmpty()) {
                    try {
                        // 把 msg 从 JSON 字符串转为 List<Map<String, Object>>
                        List<Map<String, Object>> msgList = objectMapper.readValue(history,
                                new TypeReference<List<Map<String, Object>>>() {});

                        String sessionId = key.substring(key.lastIndexOf(":") + 1);

                        Map<String, Object> entry = new HashMap<>();
                        entry.put("sessionId", sessionId);
                        entry.put("msg", msgList);
                        historyList.add(entry);
                    } catch (Exception e) {
                        // 可以记录日志或跳过错误格式的消息
                        e.printStackTrace();
                    }
                }
            }
        }
        log.info("聊天历史:" + historyList.toString());


        return new ResponseData(HttpStatus.SUCCESS, historyList);
    }

    @Override
    public ResponseData deleteConversationChatLangMessageBySessionId(String sessionId, String username) {
        String pattern = KEY_PREFIX + username + ":*";
        Set<String> keys = redisTemplate.keys(pattern);
        System.out.println(keys);
        Boolean delete = redisTemplate.delete(KEY_PREFIX + username + ":" + sessionId);
        System.out.println(delete);
        return new ResponseData(HttpStatus.SUCCESS,"对话已删除");
    }


    // 辅助方法：根据Recording生成标题（可以根据具体需求调整逻辑）
    private String generateTitle(String question) {
        // TODO 可以适当修改 简单示例：根据Recording ID生成标题

        return question;
    }
}
